<template>
    <view class="SingleQuestionPageWrap">
        <scroll-view class="scrollWrap" :scroll-y="true" :style="{ paddingBottom: safeAreaInsets.bottom + 50 +'px' }">
            <view class="flex between smallItem" @click="isSelectTypePopup = true">
                <text class="required item-center">试题类型</text>
                <view>
                    <text>{{ selectQuestData.text || "" }}</text>
                    <image src="../static/images/teachingMaterial/greyLeftArrow.svg"
                        style="width: 16rpx;height: 24rpx;margin-left: 30rpx;" />
                </view>
            </view>
            <view style="display: flex; flex-direction: column;padding: 34rpx 0 42rpx 0;" class="deBorder">
                <text class="required item-center" style="margin: 34rpx 0;">试题正文</text>
                <view style="background-color: #F9F9F9;border-radius: 24rpx;padding: 22rpx 34rpx;min-height: 180rpx;">
                    <textarea v-model="content" style="width: 100%;" placeholder="请输入试题题干正文内容" :border="'none'" :maxlength="-1"
                        :auto-height="true"></textarea>
                </view>
            </view>
            <!-- 渲染不同试题类型 -->
            <!--选择题 -->
            <view class="xzt_style deBorder"
                v-if="selectQuestData.value == questonDict.singleSelect || selectQuestData.value == questonDict.multipleSelect">
                <view style="margin: 26rpx 0 20rpx;">
                    <text class="required item-center">试题选项</text>
                </view>
                <view v-for="(item, index) in choiceQuestionArr" :key="index">
                    <view class="selectItem">
                        <view class="flex center item-center" :class="item.selectStatus ? 'active' : 'noActive'"
                            @click="onSelectAnswer(item, index, '选择题')">
                            <u-icon size="20rpx" :color="item.selectStatus ? '#FFF' : '#FFF'" name="checkmark" />
                        </view>
                        <text style="margin:0 24rpx">{{ letterNumber[index] }}</text>
                        <view class="inputStyle flex1">
                            <input placeholder="请输入选项的内容" style="height: 120rpx;width: 100%;" :border="'none'" :clearable="true"
                                v-model="item.value"></input>
                        </view>
                        <image src="./static/subTree.svg" style="margin-left: 14rpx;" class="iconStyle"
                            @click="onDelXzt(index)" />
                    </view>
                </view>
                <view class="bottomWrapStyle">
                    <text style="color: #37B874;" @click="onAddNewXzt">增加选项</text>
                    <text style="margin-left: 70rpx;color: #37B874;" @click="isBatchInputQuPopup = true">批量增加</text>
                </view>
            </view>
            <!-- 判断题 -->
            <view class="pdt_style deBorder" v-else-if="selectQuestData.value == questonDict.judge">
                <view style="margin: 26rpx 0 20rpx;">
                    <text class="required item-center">试题答案</text>
                </view>
                <view v-for="(item, index) in judgeArr" :key="index">
                    <view class="selectItem">
                        <view class="flex center item-center" :class="item.selectStatus ? 'active' : 'noActive'"
                            @click="onSelectAnswer(item, index, '判断题')">
                            <u-icon size="20rpx" :color="item.selectStatus ? '#FFF' : '#FFF'" name="checkmark" />
                        </view>
                        <text style="margin:0 24rpx">{{ letterNumber[index] }}</text>
                        <view class="itemStyle flex1 ">
                            {{ item.value }}
                        </view>
                    </view>
                </view>
            </view>
            <!-- 简答题 -->
            <view v-else-if="['si01','si02','si03','si04'].includes(selectQuestData.value)" class="jdt_style deBorder">
                <view style="margin: 26rpx 0 20rpx;">
                    <text class="required item-center">试题答案</text>
                </view>
                <view style="background-color: #F9F9F9;border-radius: 24rpx;padding: 22rpx 34rpx;min-height: 180rpx;">
                    <textarea v-model="shortAnswerData" placeholder="请输入试题答案" :border="'none'" :maxlength="-1"
                        :auto-height="true" style="width: 100%;"></textarea>
                </view>
            </view>
            <!-- 底部 -->
            <view style="display: flex; flex-direction: column;padding: 27rpx 0 32rpx 0;" class="deBorder">
                <text class="required item-center" style="margin-bottom: 32rpx">参考分值</text>
                <input class="inputStyleScore" v-model="referenceScoreData" @input="checkAmount" type="digit"
                    placeholder="请输入分值" />
            </view>
            <view style="display: flex; flex-direction: column;padding: 33rpx 0 28rpx 0;" class="deBorder">
                <text class="item-center" style="margin-bottom: 32rpx;">习题解析</text>
                <view style="background-color: #F9F9F9;border-radius: 24rpx;padding: 22rpx 34rpx;min-height: 180rpx;">
                    <textarea v-model="exerciseAnalysisData" placeholder="请输入解析内容" :border="'none'" :maxlength="-1"
                        :auto-height="true" style="width: 100%;"></textarea>
                </view>
            </view>
            <view class="flex between smallItem" v-for="item in bottomMenu" 
                @click="onHandleBottomMenu(item)">
                <text :class="item.required?'required item-center':'noRequired item-center'" 
                        style="color: #333;">{{ item.text }}</text>
                <view>
                    <text >{{ onShowBottomText(item.code)}}</text>
                    <image src="../static/images/teachingMaterial/greyLeftArrow.svg"
                        style="width: 16rpx;height: 24rpx;margin-left: 30rpx;" />
                </view>
            </view>
            <!-- 选择试题类型 -->
            <BotMenu :isPopup="isSelectTypePopup" @close="isSelectTypePopup = false" title="试题类型">
                <view v-for="item in questionData" :key="item.value" class="selectTypeItem"
                    :style="{ color: selectQuestData.value == item.value ? '#37B874' : '#000' }"
                    @click="onSelectQustion(item,'selectType')">
                    {{ item.text }}
                </view>
            </BotMenu>
            <!-- 批量录入 -->
            <BotMenu :isPopup="isBatchInputQuPopup" @close="isBatchInputQuPopup = false" title="批量增加">
                <view style="padding: 48rpx 30rpx;">
                    <view
                        style="background-color: #F9F9F9;border-radius: 24rpx;padding: 22rpx 34rpx;min-height: 180rpx;">
                        <textarea v-model="batchInputContent" :border="'none'" class="xzt-placeholder"
                            style="width:100%;min-height: 180rpx;" :placeholder="`请在此输入批量增加的选项内容，可在此增加批量选项内容，回车代表选项分割`"
                            :maxlength="-1" :auto-height="true">

                    </textarea>
                    </view>
                </view>
                <view class="okBtn center" @click="onBatchInputOk">
                    确定
                </view>
            </BotMenu>
            <!-- 选择难度 -->
            <BotMenu :isPopup="isSelectDifficultyPopup" @close="isSelectDifficultyPopup = false"  title="试题难度">
                <view v-for="item in questonDifficulty" :key="item.value" class="selectTypeItem"
                    :style="{ color: selectQuestDiff.value == item.value ? '#37B874' : '#000' }"
                    @click="onSelectQustion(item,'selectDiff')">
                    {{ item.text }}
                </view>
            </BotMenu>
        </scroll-view>
        <view class="bottomBtn" :style="{ bottom:  safeAreaInsets.bottom +'px' }" @click="onSubmit">
            <!-- <image src="../static/images/question/addTk.svg" style="width: 36rpx;height: 36rpx; margin-right: 22rpx;" /> -->
            <text>添加试题</text>
        </view>
        <!-- 选择知识机构 -->
        <SelectknowledgePopup 
            :isPopup="isSelectknowledgePopup" 
            @close="isSelectknowledgePopup = false" 
            @onSelect="onSelectKnowledge"
            title="知识机构" 
            :subjectUuid="pInfo.subjectUuid"
            :showCancel="true"/>
    </view>
</template>

<script>
import { text } from '../common/request';
import { QUESTION_TYPE, LETTER_Number, QUESTION_DICT,QUESTION_DIFFICULTY } from '../data/TestQuestionsType'
import { getArrObjectByProperty, notificationFun } from '../utils/PrjUtils';
import { saveTheoryItem,getTheoryItemByUuid } from './services/myQuestionBankService';

export default {
    data() {
        return {
            content: "",
            // 题型
            isSelectTypePopup: false,
            // 题型数据
            questionData: QUESTION_TYPE,
            // 题型dict
            questonDict: QUESTION_DICT,
            // 试题难度
            questonDifficulty:QUESTION_DIFFICULTY,
            // 选择的题型
            selectQuestData: { value: "0201", text: '单选题' },
            // 多选数量
            choiceQuestionArr: [
                { value: "", selectStatus: false },
                { value: "", selectStatus: false },
                { value: "", selectStatus: false },
                { value: "", selectStatus: false },
            ],
            // 判断题答案
            judgeArr: [
                { value: "正确", selectStatus: false },
                { value: "错误", selectStatus: false },
            ],
            // 简答题答案
            shortAnswerData: "",
            // * 参考分值
            referenceScoreData: "",
            // 试题解析
            exerciseAnalysisData: "",
            // 选择dict
            letterNumber: LETTER_Number,
            // 安全区域
            safeAreaInsets: {bottom:0},
            // 批量录入试题,
            isBatchInputQuPopup: false,
            // 批量录入试题
            batchInputContent: "",
            // 底部试题操作
            bottomMenu: [
                { text: "选择章节",code:"select", required: true },
                { text: "试题难度",code:"andu", required: true },
                { text: "编辑章节",code:"editZj", required: false },
            ],
            // 试题难度
            isSelectDifficultyPopup:false,
            // 选择试题的难度
            selectQuestDiff:{},
            // 选择知识机构弹出
            isSelectknowledgePopup:false,
            // 上层页面数据
            pInfo: {},
            // 选择的知识机构
            selectKnowledgeData:{}
        }
    },
    computed: {

    },

    methods: {
        // 选择试题
        onSelectQustion(item,type) {
            if(type=="selectType"){
                this.selectQuestData = item;
                this.isSelectTypePopup = false;
            }
            else if(type=="selectDiff"){
                this.selectQuestDiff = item;
                this.isSelectDifficultyPopup = false;
            }
           
        },
        // 选择答案
        onSelectAnswer(item, index, type) {
            if (type == "选择题") {
                let dataSource = [...this.choiceQuestionArr]
                // 如果单选题先重置
                if(this.selectQuestData.value == "0201"){
                    dataSource=dataSource.map(item=>({...item,selectStatus:false}))
                }
                dataSource[index] = { ...item, selectStatus: !item.selectStatus }
                this.choiceQuestionArr = dataSource
            }
            else {
                let newJudgeArr = this.judgeArr.map(item => ({ ...item, selectStatus: false }))
                newJudgeArr[index] = { ...item, selectStatus: !item.selectStatus }
                this.judgeArr = newJudgeArr
            }
        },
        // 新增新的选择题
        onAddNewXzt() {
            if (this.choiceQuestionArr.length >= 8) {
                return notificationFun("不能再添加选项了")
            }
            let data = [...this.choiceQuestionArr]
            data.push({ value: "", selectStatus: false })
            this.choiceQuestionArr = data;
        },
        // 删除选择题
        onDelXzt(index) {
            if (this.choiceQuestionArr.length <= 3) {
                return notificationFun("不能再减少选项了")
            }
            let data = [...this.choiceQuestionArr]
            data.splice(index, 1)
            this.choiceQuestionArr = data;
        },
        // 批量录题
        onBatchInputOk() {
            let dataArr = this.batchInputContent.split("\n");
            if ((dataArr.length + this.choiceQuestionArr.length) >= 9) {
                return notificationFun("超出最大,录入试题数")
            }
            // 最后转换的数据
            let newData = dataArr.map(item => ({ value: item, selectStatus: false }))
            this.choiceQuestionArr = [...this.choiceQuestionArr, ...newData]
            this.isBatchInputQuPopup = false
        },
        //格式化分值
        checkAmount(e) {
            // 部分情况 , 事件参数e会有一定区别, 这里只需要 e.detail.value 是输入的那个字符串即可
            let num = e.detail.value.match(/^\d*(\.?\d{0,1})/g)[0] || null;
            this.$nextTick(() => {
                this.referenceScoreData = num
            });
        },
        // 操作底部操作
        onHandleBottomMenu(record) {
            switch (record.code) {
                // 选择章节
                case "select":
                    this.isSelectknowledgePopup=true;
                    break;
                // 试题难度
                case "andu":
                    this.isSelectDifficultyPopup=true;
                    break;
                // 编辑章节
                case "editZj":
                    uni.navigateTo({
                        url: `/myQuestionBank/addQuestionBank?info=${encodeURIComponent(JSON.stringify({...this.pInfo,title:"编辑章节"}))}`
                    })
                    break;
                default:
                    break;
            }
        },
        // 显示选择的数据
        onShowBottomText(type){
            if(type=="andu"){
                return this.selectQuestDiff.text || ""
            }
            else if(type=="select"){
                return this.selectKnowledgeData.name || ""
            }
            else{
                return ""    
            }
        },
        // 选择的知识机构
        onSelectKnowledge(record){
            this.selectKnowledgeData = record
            this.isSelectknowledgePopup = false
        },
        // 添加试题
        onSubmit() {
            let arrDict={
                type:"请选择题型",
                itemText:"请输入试题正文",
                structId:"请选择章节",
                selectQuestDiff:"请选择试题难度",
                score:"请输入参考分值",
                //  analysis:"请输入试题解析"
            }
            let param={
                    // 题型
                    type:this.selectQuestData.value,
                    // 正文
                    itemText:this.content,
                    // 知识结构,
                    structId:this.selectKnowledgeData.structId,
                    // 试题难度
                    difficulty:this.selectQuestDiff.value,
                    // 参考分值
                    score:this.referenceScoreData,
                    // 试题解析
                    // analysis:this.exerciseAnalysisData
            }
            // 判断数据是否为空
            for(let key in param){
                if(!param[key]){
                    return notificationFun(arrDict[key])
                }
            }
            console.log("---34")
            // 选择题
            if(this.selectQuestData.value == "0201" || this.selectQuestData.value == "0301"){
                param.selectionList=this.choiceQuestionArr.map((item,index)=>({
                    context:item.value,
                    code:this.letterNumber[index],
                    selectStatus:item.selectStatus
                }))
                param.answer=this.choiceQuestionArr.flatMap((item,index)=>item.selectStatus?this.letterNumber[index]:"").join("")
                // param.selectionList=selectionList
                // param.selectionList=this.choiceQuestionArr.map((item,index)=>({
                //     context:item.value,
                //     code:this.letterNumber[index]
                // }))
            }
            // 判断题
            else if(this.selectQuestData.value == "0101"){
                param.answer=this.judgeArr.flatMap((item,index)=>item.selectStatus?this.letterNumber[index]:"").join("")
              
            }
            // 简答题
            else {
                param.answer=this.shortAnswerData
            }
            if(!param.answer){
                return notificationFun("答案不能为空")
            }
            // 如果编辑
            if(this.pInfo?.modelType=="edit"){
                param.id=this.pInfo.id
            }
            // console.log(param,"操作成功")
            saveTheoryItem(param).then(res => {
                notificationFun("操作成功");
                if(this.pInfo?.modelType=="edit"){
                   uni.navigateBack()
                }
                // 重置数据
                this.resetData()
            })
        },
        // 重置数据
        resetData() {
            this.content = "";
            this.selectQuestData = { value: "0201", text: '单选题' };
            this.choiceQuestionArr = [
                { value: "", selectStatus: false },
                { value: "", selectStatus: false },
                { value: "", selectStatus: false },
                { value: "", selectStatus: false },
            ];
            this.judgeArr = [
                { value: "正确", selectStatus: false },
                { value: "错误", selectStatus: false },
            ];
            this.shortAnswerData = "";
            this.referenceScoreData = "";
            this.exerciseAnalysisData = "";
            this.batchInputContent = "";
            this.selectQuestDiff = {};
            this.selectKnowledgeData = {};
        },
        // 初始化数据
        onInitEditData(uuid) {
            getTheoryItemByUuid({uuid}).then(res => {
                this.onHandelEditData(res)
            })
        },
        // 初始化数据操作
        onHandelEditData(record) {
            const {type,structId,structName,itemText,difficulty="",score,analysis,selectionList,answer}=record;
            this.selectQuestData={value:type,text:getArrObjectByProperty(QUESTION_TYPE, 'value', type)?.text};
            this.content=itemText;
            this.selectKnowledgeData={structId,name:structName};
            this.selectQuestDiff={value:difficulty,text:getArrObjectByProperty(QUESTION_DIFFICULTY, 'value', difficulty)?.text};
            this.referenceScoreData=score;
            this.exerciseAnalysisData=analysis
            this.pInfo={...this.pInfo,id:record.id}
            // 选择题
            if(type=="0201"||type=="0301"){
                this.choiceQuestionArr=selectionList.map((item)=>({
                    value:item.context,
                    selectStatus:answer.includes(item.code)
                }))
            }
            // 判断题
            else if(type=="0101"){
                this.judgeArr = this.judgeArr.map((item,index) => ({
                    value: item.value,
                    selectStatus:answer.includes(this.letterNumber[index])
                }))
            }
            // 简答题
            else{
                this.shortAnswerData=answer
            }
        }
    },
    onLoad(option) {
        let info = JSON.parse(decodeURIComponent(option.info)) || {}
        this.pInfo = info
        console.log(info,"--410")
        if(info?.modelType=="edit"){
            this.onInitEditData(info.uuid)
        }
    },

    beforeMount() {
        uni.getSystemInfo({
            success: (res) => {
                console.log(res.safeAreaInsets)
                // this.windowWidth = res.windowWidth
                // this.windowHeight = res.windowHeight
                this.safeAreaInsets = res.safeAreaInsets
            }
        })
    },
}
</script>

<style lang="scss" scoped>
.SingleQuestionPageWrap {
    height: 100vh;
    box-sizing: border-box;
    margin-bottom: 20rpx;
    .scrollWrap {
        box-sizing: border-box;
        height: 100vh;
        padding: 0 30rpx;
        background-color: #fff;

        .required:before {
            display: inline-block;
            margin-right: 8rpx;
            content: "*";
            line-height: 1;
            font-size: 32rpx;
            color: #f04134;
        }
        .noRequired:before {
            display: inline-block;
            margin-right: 8rpx;
            content: "*";
            line-height: 1;
            font-size: 32rpx;
            color: transparent;
        }
        .smallItem {
            padding: 27rpx 0 32rpx 0;
            border-bottom: 1px solid #F2F2F2;
        }

        .deBorder {
            border-bottom: 1px solid #F2F2F2;
        }

        .selectTypeItem {
            display: flex;
            justify-content: center;
            padding: 32rpx 0;
            border-bottom: 1rpx solid #eee;
        }

        .iconStyle {
            width: 40rpx;
            height: 40rpx;
            margin-left: 20rpx;
        }

        .xzt_style {
            padding-bottom: 40rpx;

            .selectItem {
                display: flex;
                align-items: center;
                margin-bottom: 30rpx;

                .inputStyle {
                    box-sizing: border-box;
                    height: 90rpx;
                    background: #F9F9F9;
                    display: flex;
                    align-items: center;
                    border-radius: 24rpx;
                    padding: 0 20rpx;
                }



            }

            .bottomWrapStyle {
                margin-top: 64rpx;
                display: flex;
                justify-content: flex-end;
            }

            .xzt-placeholder::placeholder {
                white-space: pre-wrap;
                /* 其他样式 */
            }
        }

        .pdt_style {
            padding-bottom: 40rpx;

            .selectItem {
                display: flex;
                align-items: center;
                margin-bottom: 30rpx;

                .itemStyle {
                    box-sizing: border-box;
                    height: 80rpx;
                    display: flex;
                    align-items: center;
                    padding: 0 20rpx;
                }
            }

            .bottomWrapStyle {
                margin-top: 64rpx;
                display: flex;
                justify-content: flex-end;
            }
        }

        .jdt_style {
            padding-bottom: 40rpx;

            .selectItem {
                display: flex;
                align-items: center;
                margin-bottom: 30rpx;

            }

        }

        .active {
            background: rgba(55, 184, 116, 1);
            border-radius: 50%;
            /* padding: 4rpx; */
            width: 13px;
            height: 13px;
            border: 1px solid rgba(55, 184, 116, 1);
        }

        .noActive {
            background: #FFF;
            border-radius: 50%;
            /* padding: 2px; */
            width: 13px;
            height: 13px;
            border: 1px solid #F2F2F2;
        }

        .okBtn {
            padding: 32rpx;
            border-top: 1px solid #EEEEEE;
        }

        .inputStyleScore {
            height: 80rpx;
            border-radius: 24rpx;
            background-color: #F9F9F9;
            padding-left: 20rpx;
        }
    }
    .bottomBtn {
            width: calc(100% - 60rpx);
            display: flex;
            align-items: center;
            justify-content: center;
            height: 90rpx;
            box-shadow: 0px 1px 8px 0px #00000014;
            border-radius: 24rpx;
            position: absolute;
            left: 30rpx;
            background-color: #37B874;
            color: #fff;
        }

}
</style>
